package com.mimo.logic.message.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import com.mimo.common.configuration.limit.aspect.IAccessLimitService;
import com.mimo.common.logic.dto.msg.BaseDispatchMessage;
import com.mimo.common.logic.dto.msg.DispatchMsgType;
import com.mimo.common.logic.dto.msg.Peer2RoomMessage;
import com.mimo.logic.message.config.MessageUpstreamConstraintsConfig;
import com.mimo.logic.message.config.MessageUpstreamConstraintsConfig.UpstreamConstraintsItem;
import com.mimo.logic.message.service.IMessageUpstreamConstraintsService;

@Service
@EnableConfigurationProperties(value = { MessageUpstreamConstraintsConfig.class })
public class MessageUpstreamConstraintsServiceImpl implements IMessageUpstreamConstraintsService {

  private static final String ROOM_MSG_LIMIT_PATTERN = "logic:msg:constraint:room:%s";// logic:msg:constraint:room:roomId
  private static final String PEER_MSG_LIMIT_PATTERN = "logic:msg:constraint:peer:%s";// logic:msg:constraint:peer:userId

  @Autowired
  private IAccessLimitService accessLimitService;

  @Autowired
  private MessageUpstreamConstraintsConfig messageUpstreamConstraintsConfig;

  @Override
  public boolean checkPeerUpstreamConstraint(BaseDispatchMessage evt) {
    UpstreamConstraintsItem constraint = messageUpstreamConstraintsConfig.getUpstreams().get(DispatchMsgType.P2P);
    String key = String.format(PEER_MSG_LIMIT_PATTERN, evt.getFrom());
    return accessLimitService.accessIncr(key, constraint.getCount(), constraint.getDuration().toMillis());
  }

  @Override
  public boolean checkP2RoomConstraint(Peer2RoomMessage evt) {
    UpstreamConstraintsItem constraint = messageUpstreamConstraintsConfig.getUpstreams().get(DispatchMsgType.Peer2Room);
    String key = String.format(ROOM_MSG_LIMIT_PATTERN, evt.getTarget());
    return accessLimitService.accessIncr(key, constraint.getCount(), constraint.getDuration().toMillis());
  }

}
